import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login')
  },
  // 模板页面
  {
    path: '',
    component: () => import('@/views/layout'),
    children: [
      // 学员列表页面
      {
        path: '/',
        name: 'student',
        component: () => import('@/views/students')
      },
      // 设置页面
      {
        path: '/setting',
        name: 'setting',
        component: () => import('@/views/setting')
      }
    ]
  },
  {
    path: '*',
    name: '404',
    component: () => import('@/views/404')
  }
]

const router = new VueRouter({
  routes
})

// 解决 冗余导航报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    if (store.state.finalUser) {
      next()
      return
    }
    next('/login')
  }
  next()
})

export default router
